package com.qf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.qf.dao.UserDao;
import com.qf.model.Telbook;
import com.qf.model.User;
import com.qf.utils.JDBCUtil;

public class UserDaoImpl implements UserDao {

	@Override
	public boolean addContactor(String cname, String ctel, String caddress, String cremark, int uid, int tid) throws SQLException {
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		boolean flag = false;
		String sql = "insert into contact values(null,?,?,?,?,?,?);";
		ps = conn.prepareStatement(sql);
		ps.setString(1, cname);
		ps.setString(2, ctel);
		ps.setString(3, caddress);
		ps.setString(4, cremark);
		ps.setLong(5, uid);
		ps.setLong(6, tid);
		int state = ps.executeUpdate();
		if(state == 1){
			flag = true;
		}
		JDBCUtil.close(conn, ps);
		return flag;
	}

	@Override
	public User findByNameAndPwd(String uname, String upwd) {
		Connection conn =null;
		PreparedStatement pstat=null;
		ResultSet rs=null;
		User u=null;
		try {
			conn= JDBCUtil.getConnection();
			pstat=conn.prepareStatement("select * from user where uname=? and upwd=?");
			pstat.setString(1, uname);
			pstat.setString(2, upwd);
			rs=pstat.executeQuery();
			if(rs.next()){
				u=new User();
				u.setUid(rs.getInt("uid"));
				u.setUpwd(rs.getString("upwd"));
				u.setUname(rs.getString("uname"));
			}
			
		} catch (Exception e) {
		}
		
		JDBCUtil.close(conn, pstat, rs);
		return u;
		
	}

	@Override
	public boolean deleteContaxtor(int cid) throws SQLException {
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		boolean flag = false;
		String sql = "insert into contact where cid=?;";
		ps = conn.prepareStatement(sql);
		ps.setInt(1, cid);
		int state = ps.executeUpdate();
		if(state == 1){
			flag = true;
		}
		JDBCUtil.close(conn, ps);
		return flag;
	}

	@Override
	public List<Telbook> showAll(int uid) {
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs=null;
		Telbook book=null;
		List<Telbook> list=new ArrayList<>();
		try{
		conn=JDBCUtil.getConnection();
		
		String sql = "select * from Telbook where cid=?;";
		ps = conn.prepareStatement(sql);
		ps.setInt(1, uid);
		//int state = ps.executeUpdate();
		if(rs.next()){
			book=new Telbook();
			book.setTid(rs.getInt("tid"));
			book.setTname(rs.getString("tname"));
			book.setUid(rs.getInt("uid"));
			list.add(book);
		}
		}catch (Exception e){
			
		
		JDBCUtil.close(conn, ps);
		
	}
		return list;

	
	}
	
}
